﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using System.IO;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using System.Xml.Linq;
using System.Reflection.Metadata;
using OfficeOpenXml.FormulaParsing.Excel.Functions.RefAndLookup;
using Castle.Core.Resource;
using MailKit.Search;

namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    ///  组件CRM创建关务装箱清单
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class GZCRMCreatePackingListController : ControllerBase
    {
        private readonly ILogger _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;
        public readonly string con_zh;
        public readonly string con_qh;
        public readonly string con_yb;


        public GZCRMCreatePackingListController(ILogger<GZCRMCreatePackingListRequestDto> logger, IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration, ILoggerFactory loggerFactory)
        {
            _WMSTokenCheckService = wmsTokenCheckService;
            con = _configuration.GetConnectionString("DDM_DbConnection_ZH");
            con_zh = _configuration.GetConnectionString("WMSDbConnection_ZH");
            con_qh = _configuration.GetConnectionString("WMSDbConnection");
            con_yb = _configuration.GetConnectionString("WMSDbConnection_YB");
            _logger = loggerFactory.CreateLogger<GZCRMCreatePackingListController>();
        }

        /// <summary>
        /// 组件CRM创建关务装箱清单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostCRMCreatePackingList([FromBody] GZCRMCreatePackingListRequestDto strparm)
        {
            string strMsg = "";
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            Dictionary<string, string> dic = new Dictionary<string, string>(); //查询公用dic
            GZCRMCreatePackingListResponseDto re = new GZCRMCreatePackingListResponseDto();

            GW_AddPackingListRequestDto input = new GW_AddPackingListRequestDto();
            List<GW_AddPackingList_Data_Dto> input_data = new List<GW_AddPackingList_Data_Dto>();
            GW_AddPackingList_IfInfo_Dto input_info = new GW_AddPackingList_IfInfo_Dto();

            try
            {
                if (strparm.rows!=null)
                {
                    int j = 1;
                    foreach (var item in strparm.rows)
                    {

                        List<GW_AddPackingList_DataDetailes_Dto> inp_de = new List<GW_AddPackingList_DataDetailes_Dto>();
                        

                        if (DB.ToInt(item.pallets_qty) > 0)
                        {
                            for (int i = 1; i <= DB.ToInt(item.pallets_qty); i++)
                            {
                                inp_de.Add(new GW_AddPackingList_DataDetailes_Dto
                                {
                                    LINENUM =i,
                                    BILLNO_PLAN = strparm.shipment_no,
                                    LINENUM_PLAN = j,
                                    TRADEMODE = strparm.TRADEMODE,
                                    DUTYMODE = item.DUTYMODE,
                                    GOODSTYPE = 2,
                                    ERPGNO = item.material_code,
                                    ERPGNAME = item.material_name,
                                    ERPGMODEL = item.ERPGMODEL,
                                    LOADQTY = DB.ToInt(item.pallets_qty)* DB.ToInt(item.pallet_amount),
                                    ERPUNIT = item.ERPUNIT,
                                    PRICE = DB.ToDouble(item.PRICE),
                                    AMOUNT = item.AMOUNT,
                                    CURR = item.CURR,
                                    PIECES = DB.ToInt(item.pallet_amount),
                                    VOLUME = DB.ToDouble(item.pallet_volume),
                                    NETWT = DB.ToDouble(item.pallet_nweight),
                                    GROSSWT = DB.ToDouble(item.pallet_gweight),
                                    ORIGINCOUNTRY = item.ORIGINCOUNTRY,
                                    BOXNO = strparm.shipment_no + "_" + item.line_no + "_" + i.ToString(),
                                    TRANSMODE=strparm.TRANSMODE,
                                    PACKAGECODE=item.PACKAGECODE,
                                    PRICE_PO=item.PRICE_PO,
                                    AMOUNT_PO=item.AMOUNT_PO,
                                    DESTINATIONCOUNTRY = strparm.DESTINATIONCOUNTRY


                                });
                            }
                        }
                        else
                        {
                            strMsg = "行<" + item.line_no + ">总托数数量获取失败，生成装箱清单失败！";
                        }


                        if (inp_de.Count>0)
                        {
                            input_data.Add(new GW_AddPackingList_Data_Dto
                            {
                                COPID = strparm.COPID,
                                LISTBILLNO = strparm.shipment_no,
                                LOADDATE = strparm.shipment_date,
                                COPINNCODE_VC = strparm.customer_no,
                                VCOPFULLNAME = strparm.customer_name,
                                DELIVERYADDR = item.DELIVERYADDR,
                                BILLNO_SOG = strparm.BILLNO_SOG,
                                INVOICENO = strparm.INVOICENO,
                                FROMCOUNTRY= strparm.FROMCOUNTRY,
                                TRADECOUNTRY=strparm.TRADECOUNTRY,
                                DETAILED = inp_de
                            });

                        }
                        j++;
                    }

                    if (input_data.Count>0)
                    {
                        input_info.MSGID = strparm.MSGID;
                        input_info.IFID = strparm.IFID;
                        input_info.RECEIVER = strparm.RECEIVER;
                        input_info.ASYN = strparm.ASYN;
                        input_info.SENDER = strparm.SENDER;

                        input.IFINFO = input_info;
                        input.DATA = input_data;

                        if (input!=null)
                        {
                            Dictionary<string, string> urldic = new Dictionary<string, string>(); //URL获取dic
                            urldic.Add("function_description", "关务装柜清单柜号信息更新");//查看URL配置表地址描述
                            DataTable url_dt = MethodHelp.GetTableInfo("TMS0004", urldic, con);//获取URL地址
                            if (url_dt.Rows.Count>0)
                            {
                                string jsonText = JsonConvert.SerializeObject(input);
                                var reAgv = DB.httpPost(url_dt.Rows[0]["interface_url"].ToString(), jsonText, "", "否");
                                GW_AddPackingList_Re_Dto psp = JsonConvert.DeserializeObject<GW_AddPackingList_Re_Dto>(reAgv);
                                if (psp.STATE != "S")
                                {
                                    strMsg = psp.MSG;
                                }
                            }
                        }
                    }
                    else
                    {
                        strMsg = "送货单<" + strparm.shipment_no + ">创建装箱信息接口明细生成失败！";
                    }

                   
                }
            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

            if (strMsg == "")
            {
                re.code = 0;
                re.message = "";
            }
            else
            {
                re.code = 500;
                re.message = strMsg;

            }


            _logger.LogInformation(JsonConvert.SerializeObject(re));
            return new JsonResult(re);

        }


    }
}
